<script lang="ts" setup>
import type { PropType } from 'vue'

const props = defineProps({
  // 速度比率，以最外层容器的宽度为基准
  speedRatio: {
    type: Number as PropType<number>,
    validator(value: number) {
      return value > 0 && value < 1
    },
    default: 0.3,
  },
  text: {
    type: String as PropType<string>,
    required: true,
  },
})
const scrollRef = ref<HTMLDivElement>()
const duration = ref(0)
const delay = Math.floor(Math.random() * 1000 + 400) / 1000
onMounted(() => {
  // 根据速度计算动画时间
  duration.value = Math.ceil(scrollRef.value!.offsetWidth / (scrollRef.value!.offsetWidth * props.speedRatio))
})
</script>

<template>
  <div
    ref="scrollRef"
    class="scroll-container" :style="{
      animationDuration: `${duration}s`,
      animationDelay: `${delay}s`,
    }"
  >
    <div class="no-scroll" :data-text="props.text">
      {{ props.text }}
    </div>
    <div class="scroll-item" :data-text="props.text">
      {{ props.text }}
    </div>
  </div>
</template>

<style>
.scroll-container {
  position: relative;
  line-height: 2;
  height: 2em;
  overflow: hidden;
  width: inherit;
  background-color: white;
}

.no-scroll {
  display: block;
  max-height: 4em;
}

.scroll-item {
  display: inline-block;
  white-space: nowrap;
  line-height: 30px; /* 控制每条滚动文字的行高 */
  animation: scroll-text 5s linear infinite; /* 控制滚动速度和动画效果 */
  position: relative;
  top: -4em;
  background-color: inherit;
}

.scroll-item::after {
  content: attr(data-text);
  padding: 0 5em;
  font-size: inherit;
}

@keyframes scroll-text {
  to {
    transform: translateX(-50%);
  }
}
</style>
